package com.refusea.train.config

import com.alibaba.fastjson2.JSONWriter
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter
import org.springframework.boot.autoconfigure.http.HttpMessageConverters
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.http.MediaType

@Configuration
class FastJson2Config {

    @Bean
    @Primary
    fun fastJsonHttpMessageConverters(): HttpMessageConverters {

        val converter = FastJsonHttpMessageConverter()

        converter.supportedMediaTypes = listOf(MediaType.APPLICATION_JSON)
        converter.fastJsonConfig.setWriterFeatures(
            // 非字符串的 key 以字符串输出
            JSONWriter.Feature.WriteNonStringKeyAsString,
            // 枚举类型以 toString 输出
            JSONWriter.Feature.WriteEnumUsingToString,
            // null list 输出 []
            JSONWriter.Feature.WriteNullListAsEmpty,
            // original features
            *converter.fastJsonConfig.writerFeatures
        )

        return HttpMessageConverters(converter)
    }
}
